import Timer from '../utils/timer'

function initTimer () {
  this.timer = {}
  this.timer.loading = new Timer({type: 'loading', gap: 100})
  this.timer.info = new Timer({type: 'info', gap: 1000})
  this.timer.fps = new Timer({type: 'fps', isRaf: true})

  // loading timer
  let lastPlayPos = 0
  let currentPlayPos = 0
  let bufferingDetected = false
  this.timer.loading.on('tick', ({isStop}) => {
    if (isStop) {
      return
    }
    currentPlayPos = this.dom.video.currentTime
    if (
      !bufferingDetected &&
      currentPlayPos === lastPlayPos &&
      !this.dom.video.paused
    ) {
      bufferingDetected = true
      this.trigger('internal_buffer', true)
    }
    if (
      bufferingDetected &&
      currentPlayPos > lastPlayPos &&
      !this.dom.video.paused
    ) {
      bufferingDetected = false
      this.trigger('internal_buffer', false)
    }
    lastPlayPos = currentPlayPos
  })

  // info timer
  this.timer.info.on('tick', ({isStop}) => {
    if (!isStop) {
      // this.player.infoPanel.update()
    }
  })

  // fps timer
  let fpsStart
  let fpsIndex; // eslint-disable-line
  this.timer.info.on('fps', ({isStop}) => {
    if (!isStop) {
      if (!fpsStart) {
        fpsStart = new Date()
        fpsIndex = 0
      } else {
        fpsIndex++
        const fpsCurrent = new Date()
        if (fpsCurrent - fpsStart > 1000) {
          // this.player.infoPanel.fps(
          //   (this.fpsIndex / (fpsCurrent - this.fpsStart)) * 1000
          // )
          fpsStart = new Date()
          fpsIndex = 0
        }
      }
    } else {
      fpsStart = 0
      fpsIndex = 0
    }
  })

  this.timer.loading.start()
  this.timer.info.start()
}

export default initTimer
